package it.happyisland.framework.web.core;

import it.happyisland.framework.web.core.Results.Forward;
import it.happyisland.framework.web.core.Results.Html;
import it.happyisland.framework.web.core.Results.Json;
import it.happyisland.framework.web.core.Results.ProceedFilterChain;
import it.happyisland.framework.web.core.Results.Redirect;
import it.happyisland.framework.web.core.Results.ResponseError;
import it.happyisland.framework.web.core.Results.Text;
import it.happyisland.framework.web.core.Results.Xml;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Responder {
	public void render(HttpServletRequest req, HttpServletResponse resp, FilterChain chain, Object result) throws ServletException, IOException {
		if(result == null){
			return;
		}
		if(result instanceof String){
			render(req, resp, chain, new Html((String) result));
			return;
		}
		if(result instanceof Text){
			Text text = (Text) result;
			write(resp, text.value, "text/plain");
			return;
		}
		if(result instanceof Html){
			Html html = (Html) result;
			write(resp, html.value, "text/html");
			return;
		}
		if(result instanceof Xml){
			Xml xml = (Xml) result;
			write(resp, xml.value, "application/xml");
			return;
		}
		if(result instanceof Json){
			Json json = (Json) result;
			write(resp, json.value, "application/json");
			return;
		}
		
		
		if(result instanceof Forward){
			Forward forward = (Forward) result;
			req.getRequestDispatcher(forward.path).forward(req, resp);
			return;
		}
		
		if(result instanceof Redirect){
			Redirect redirect = (Redirect) result;
			resp.sendRedirect( redirect.path );
			return;
			
		}
		if(result instanceof ResponseError){
			ResponseError error = (ResponseError) result;
			resp.sendError(error.code);
			return;
		}
		if(result instanceof ProceedFilterChain){
			if(chain == null){
				throw new ServletException("Filter chain allowed only in Filters");
			}
			chain.doFilter(req, resp);
			return;
		}
		
		throw new ServletException(result.getClass() + " cannot be rendered");
	}
	
	private void write(HttpServletResponse resp, String value, String type) throws IOException{
		if(type != null){
			 resp.setContentType(type);
		}
		
		Writer writer;
		writer = resp.getWriter();
		writer.append(value);
		writer.flush();
		writer.close();
		
	}

	
}
